const multer = require("multer");
const fs = require("fs");
const path = require("path");

function createUploadMiddleware() {
  // 定义固定的存储引擎
  const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      // 根据日期生成目录路径
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, "0");
      const day = String(today.getDate()).padStart(2, "0");
      const directoryPath = `public/uploads/${year}/${month}/${day}/`;

      // 确保目录存在，不存在则创建
      if (!fs.existsSync(directoryPath)) {
        fs.mkdirSync(directoryPath, { recursive: true });
      }
      cb(null, directoryPath);
    },
    filename: (req, file, cb) => {
      let decodedFileName = decodeURIComponent(file.originalname);
      const safeFileName =
        path.basename(decodedFileName, path.extname(decodedFileName)) +
        "_" +
        Date.now() +
        path.extname(decodedFileName);
      file.originalname = safeFileName;
      cb(null, safeFileName);
    },
  });

  // 固定的multer实例配置
  const multerInstance = multer({
    storage: storage,
    limits: { fileSize: 1024 * 1024 * 1024 }, // 1GB大小限制
  });

  /**
   * 单文件上传处理器
   * @param {string} fieldName - 表单字段名
   * @returns {Function} 中间件函数
   */
  const singleFileUpload = (fieldName) => {
    return (req, res, next) => {
      multerInstance.single(fieldName)(req, res, (err) => {
        if (err) {
          handleUploadError(res, err);
        } else {
          next(); // 文件上传成功，继续到下一个中间件
        }
      });
    };
  };

  /**
   * 多文件上传处理器
   * @param {string} fieldName - 表单字段名
   * @returns {Function} 中间件函数
   */
  const multipleFileUpload = (fieldName) => {
    return (req, res, next) => {
      multerInstance.array(fieldName, 20)(req, res, (err) => {
        // 最多允许上传20个文件
        if (err) {
          handleUploadError(res, err);
        } else {
          next(); // 文件上传成功，继续到下一个中间件
        }
      });
    };
  };

  // 错误处理函数
  const handleUploadError = (res, err) => {
    if (err.code === "LIMIT_FILE_SIZE") {
      res.status(400).send("文件大小超过1GB限制！");
    } else if (err.code === "LIMIT_UNEXPECTED_FILE") {
      res.status(400).send("上传文件个数超过20个的限制！");
    } else {
      console.error(err);
      res.status(500).send("上传文件时出错！");
    }
  };

  return { singleFileUpload, multipleFileUpload };
}

module.exports = createUploadMiddleware;
